package com.atguigu.scw.manager.service.impl;

import com.atguigu.scw.manager.bean.TPermission;
import com.atguigu.scw.manager.dao.TPermissionMapper;
import com.atguigu.scw.manager.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements PermissionService {
    private final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);
    @Autowired
    TPermissionMapper permissionMapper;

    @Override
    public List<TPermission> getAllMenus() {
        // 存放父菜单，但是将children属性赋值
        List<TPermission> returnMenuList = new ArrayList<>();
        Map<Integer, TPermission> cacheMap = new HashMap<>();
        List<TPermission> allMenuList = permissionMapper.selectByExample(null);

        // 将所有菜单放到Map中
        // 都是引用，如果从map中拿到的数据，改变以后，map中也会改变
        for (TPermission menu : allMenuList) {
            cacheMap.put(menu.getId(), menu);
        }

        // 适用于二级菜单
        for (TPermission menu : allMenuList) {
            if (menu.getPid() == 0) {
                // 父菜单
                returnMenuList.add(menu);
            } else {
                // 子菜单，加入到父菜单中
                // 根据子菜单的pid，拿到父菜单
                TPermission parentMenu = cacheMap.get(menu.getPid());
                // 拿到父菜单的子菜单
                List<TPermission> childrenList = parentMenu.getChildren();
                if (childrenList != null) {
                    // 当前有子菜单
                    childrenList.add(menu);
                } else {
                    // 当前没有子菜单
                    childrenList = new ArrayList<>();
                    // 添加当前子菜单
                    childrenList.add(menu);
                    // 将当前整理好的children设置进去
                    parentMenu.setChildren(childrenList);
                }
            }
        }
        logger.debug("菜单列表：{}", returnMenuList);
        return returnMenuList;
    }

    @Override
    public List<TPermission> getPermissions() {
        return permissionMapper.selectByExample(null);
    }

    @Override
    public void savePermission(TPermission permission) {
        permissionMapper.insertSelective(permission);
    }

    @Override
    public TPermission getMenuById(Integer id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateMenu(TPermission permission) {
        permissionMapper.updateByPrimaryKeySelective(permission);
    }

    @Override
    public void deleteMenuById(Integer id) {
        permissionMapper.deleteByPrimaryKey(id);
    }
}